package com.bosch.in.rtp1.ept.action;

import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.List;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONSerializer;
import net.sf.jxls.exception.ParsePropertyException;

import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.MappingDispatchAction;

import com.bosch.in.rtp1.ept.action.form.FinishedRecipeCriteriaForm;
import com.bosch.in.rtp1.ept.constant.FinishRecipeConstant;
import com.bosch.in.rtp1.ept.manager.ChartManager;
import com.bosch.in.rtp1.ept.manager.FinishRecipeManager;
import com.bosch.in.rtp1.ept.model.dto.FshRcpChartValues;
import com.bosch.in.rtp1.ept.model.dto.FshRcpRecord;
import com.bosch.in.rtp1.ept.model.dto.JsonFactors;
import com.bosch.in.rtp1.ept.model.technical.Condition4FinishRecipe;
import com.bosch.in.rtp1.ept.model.technical.FinishedRecipeWrapper;
import com.bosch.in.rtp1.ept.util.ConverterUtility;
import com.bosch.in.rtp1.ept.util.ExporterUtility;
import com.bosch.in.rtp1.ept.util.ManagerFactory;
import com.bosch.in.rtp1.ept.util.SQLConditionBuilder;
import com.bosch.in.rtp1.ept.util.StringUtility;

public class FshRcpDiagramAction extends MappingDispatchAction{
    
	/**
     * Report template file to export to excel
     */
    private static final String EXCEL_TEMPLATE_FILE = "templates/fshRcpReport_template.xls";
    
    private static final Logger LOGGER = Logger.getLogger(FshRcpDiagramAction.class);
    
	/**
	 * Response to export to excel click, it will delegate to Manager class
	 * to query the x-factors for chart according to search criteria in request parameter.
	 * The result list then will be save to excel file and returns to client
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws SQLException 
	 * @throws InvalidFormatException 
	 * @throws ParsePropertyException 
	 * @throws IOException 
	 */
	public ActionForward exportDiagramExcel(ActionMapping mapping,ActionForm form,
			HttpServletRequest request,HttpServletResponse response) throws SQLException, ParsePropertyException, InvalidFormatException, IOException 
			 {
	
		LOGGER.debug("Begin FshRcpDiagramAction.exportDiagramExcel");
		
		// load excel template
		InputStream is = this.getServlet().getServletContext().getResourceAsStream(EXCEL_TEMPLATE_FILE);
		
		// extract conditions from request
		Condition4FinishRecipe condition4FinishRecipe = SQLConditionBuilder.extractCondition4FinishRecipe(request);
		
		// load FinishedRecipeManager instance
		FinishRecipeManager finishRecipeManager = ManagerFactory.getInstance().getFinishRecipeManager();
		
		// get ChartValues list for this chart
		List<FshRcpChartValues> chartValues = finishRecipeManager.getFactorList(condition4FinishRecipe);
		
		// MIME type is excel
        response.setContentType("application/vnd.ms-excel");
        
        // offer the user the ability to download and save the resulting Excel file
        response.setHeader("Content-Disposition","attachment; filename=FshRecipeChart.xls");
        
        if (chartValues.size()>0)
        {
        	// create excel workbook
        	HSSFWorkbook workbook = ExporterUtility.exportDataChart(chartValues.get(0).getFshRcpChartFactors(), is, condition4FinishRecipe);
        	// send created excel workbook to client
        	ServletOutputStream out = response.getOutputStream();
        	workbook.write(out);
        	out.flush();
        }
        
        LOGGER.debug("End FshRcpDiagramAction.exportDiagramExcel");
        
        return null;
	}
	
	/**
	 * Response the list of String which represent the path lead to charts
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws SQLException 
	 * @throws IOException 
	 */
	public ActionForward displayFshRcpDiagram(ActionMapping mapping,ActionForm form,
			HttpServletRequest request,HttpServletResponse response) throws SQLException, IOException 
			 {
		
		LOGGER.debug("Begin FshRcpDiagramAction.displayFshRcpDiagram");
		
		// extract conditions from request
		Condition4FinishRecipe condition4FinishRecipe = SQLConditionBuilder.extractCondition4FinishRecipe(request);
		
		// get FinishRecipeManager instance
		FinishRecipeManager finishRecipeManager = ManagerFactory.getInstance().getFinishRecipeManager();
		
		// retrieve location list, stage list, and eqptype list  
		FinishedRecipeWrapper frWrapper = finishRecipeManager.getFinishedRecipesWrapper(condition4FinishRecipe);
		((FinishedRecipeCriteriaForm)form).setLocations(frWrapper.getLocations());
		((FinishedRecipeCriteriaForm)form).setStages(frWrapper.getStages());
		((FinishedRecipeCriteriaForm)form).setEqpTypes(frWrapper.getEqpType());
		
		// get ChartManager instance
		ChartManager chartManager = ManagerFactory.getInstance().getChartManager();
		
		// get string list which represents paths of charts
		List<String> chartList = chartManager.getFshRcpsChart(frWrapper.getChartValues(), request, response, condition4FinishRecipe.getYear());
		
		// send paths of charts to client
		request.setAttribute(FinishRecipeConstant.FNSH_RECP_CHART_LIST, chartList);
		
		// set current conditions
		request.setAttribute(FinishRecipeConstant.PART_ID_PARAM_HIDDEN	, StringUtility.convertToEmptyIfNull(condition4FinishRecipe.getPartId()));
		request.setAttribute(FinishRecipeConstant.EQPTYPE_PARAM_HIDDEN	, StringUtility.convertToEmptyIfNull(condition4FinishRecipe.getEqpType()));
		request.setAttribute(FinishRecipeConstant.EQUIPID_PARAM_HIDDEN	, StringUtility.convertToEmptyIfNull(condition4FinishRecipe.getEquipID()));
		request.setAttribute(FinishRecipeConstant.STAGE_PARAM_HIDDEN	, StringUtility.convertToEmptyIfNull(condition4FinishRecipe.getStage()));
		request.setAttribute(FinishRecipeConstant.LOCATION_PARAM_HIDDEN	, StringUtility.convertToEmptyIfNull(condition4FinishRecipe.getLocation()));
		request.setAttribute(FinishRecipeConstant.YEAR_PARAM_HIDDEN		, condition4FinishRecipe.getYear());
		request.setAttribute(FinishRecipeConstant.CUSTOMER_PARAM_HIDDEN	, StringUtility.convertToEmptyIfNull(condition4FinishRecipe.getCustomerName()));
		
		LOGGER.debug("End FshRcpDiagramAction.displayFshRcpDiagram");
		
    	// Forward to form page
        return mapping.findForward("success");
	}
	
	/**
	 * Response to ajax call from Jquery grid, it will delegate to Manager class
	 * to query FshRcpRecord according to search criteria in request parameter.
	 * The returned list then will be transformed to JSON format in order to 
	 * display on client side.
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws SQLException 
	 * @throws IOException 
	 */
	@SuppressWarnings("unchecked")
	public ActionForward loadXFactorDetailTable(ActionMapping mapping,ActionForm form,
			HttpServletRequest request,HttpServletResponse response) throws SQLException, IOException 
			 {

		LOGGER.debug("Begin FshRcpDiagramAction.loadXFactorDetailTable");
		
		// extract conditions from request
		Condition4FinishRecipe condition4FinishRecipe = SQLConditionBuilder.extractCondition4FinishRecipe(request);
		
		// get FinishRecipeManager instance
		FinishRecipeManager finishRecipeManager = ManagerFactory.getInstance().getFinishRecipeManager();
		
		// retrieve FshRcpRecord list according to the conditions
		List<FshRcpRecord> fshRcpRecords = finishRecipeManager.getFinishedRecipes(condition4FinishRecipe);
				
    	// convert returned data in kind of JSON format which Jqgrid supports
    	JSONArray cellarray = ConverterUtility.convertFshRcpRecordsToRows(fshRcpRecords, condition4FinishRecipe.getFactorType());
    	JsonFactors jsonFactors = new JsonFactors();
    	jsonFactors.setRows(cellarray);
    	
    	// write data to output stream with MIME type is text
    	String jsonResponse = JSONSerializer.toJSON(jsonFactors).toString();
    	response.setContentType("text/text;charset=utf-8");
    	response.setHeader("cache-control", "no-cache");
    	PrintWriter out = response.getWriter();
    	out.println(jsonResponse);
    	out.flush();
    	
    	LOGGER.debug("End FshRcpDiagramAction.loadXFactorDetailTable");
    	
    	return null;
	}
	
	
}

